<template>
  <div class="login-container">
    <div class="top-text">上善若水-颐养中心后台管理系统</div>
    <div class="login-box">
      <h3 class="login-title">请登录</h3>
      <el-form :model="loginForm" ref="loginFormRef">
        <el-form-item label="登录名" prop="name" :rules="[{ required: true, message: '请输入登录名', trigger: 'blur' }]">
          <el-input type="text" v-model="loginForm.name" size="small"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pswd" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
          <el-input type="password" v-model="loginForm.pswd"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="login-button" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
      <div class="error-message">{{ errorMsg }}</div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import router from "@/util/router";
import http from '@/axios/http';
import qs from "qs";
import { useUserStore } from '@/store/userStore';

const loginForm = reactive({
  name: '',
  pswd: ''
});
const loginFormRef = ref(null); // 用于表单验证
const errorMsg = ref(''); // 使用 ref 创建响应式变量

function login() {
  // 验证表单
  loginFormRef.value.validate((valid) => {
    if (!valid) {
      return; // 如果验证不通过，直接返回
    }

    const logindata = {
      username: loginForm.name,
      password: loginForm.pswd
    };

    http.post('/lyy/login', qs.stringify(logindata)).then((res) => {
      let result = res.data; // 处理器返还的结果数据

      if (result.result === "success") { // 返还标志是 "success"
        console.log(result.data);  // 打印返还的数据

        // 设置用户信息
        let loginUser = result.data;
        console.log('当前用户:' + loginUser.username);

        // 存token
        let token = loginUser.token;
        let userStore = useUserStore();
        userStore.setToken(token);
        userStore.setUserrole(loginUser.roleId);
        userStore.getToken;

        router.push({
          path: '/',
          state: result.data
        });
      } else if (result.error === "user_not_found") {
        errorMsg.value = "未查询到该账号，请联系管理员添加注册";
      } else if (result.error === "password_mismatch") {
        errorMsg.value = "账号或密码输入错误，请重新输入";
      } else {
        errorMsg.value = result.error || "登录失败，请稍后再试";
      }
    }).catch((error) => {
      console.error("登录请求失败", error);
      errorMsg.value = "登录请求失败，请稍后再试";
    });
  });
}


function goToForgotPassword() {
  router.push('/ForgotPassword');
}
</script>

<style scoped>
@import '../styles/loginStyles.css';
</style>